package com.topcent.tioxyc.consumer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author: weidian
 * @date: 2024/10/15 15:23
 * @Description: SAP销售订单消费
 */
@Component
@RabbitListener(queues = "queue_b")
@Slf4j
public class SalesOrderConsumer {
    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";
    private static final String DATA_DELETE = "data_remove";

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 处理 payload 消息
            //System.out.println("Received payload: " + msg);
            // 在这里执行具体的业务逻辑

            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            //op:推送事件；包括data_create(数据提交)、data_update(数据修改)、data_remove(数据删除)、data_recover(数据恢复)
            String op = payloadJSON.getStr("op");
            //data:具体数据内容
            String data = payloadJSON.getStr("data");

            if (DATA_CREATE.equals(op)) {
                create(data);
            } else if (DATA_UPDATE.equals(op)) {
                update(data);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息 deliveryTag：消息唯一标识符。false：仅拒绝当前消息。true：消息重新入队，供后续重试。
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    private void update(String data) {
        SalesOrder salesOrder = JSONUtil.toBean(data, SalesOrder.class);
        //2表示流程手动结束；1表示流程已完成；0表示流程进行中
        if (salesOrder.getFlowState() == 1) {
            Header[] headers = ConnmeUtils.createHeaders();

            //销售组给null
            salesOrder.set_widget_1718759603978(null);

            List<String> str = new ArrayList<>();
            str.add("_widget_1718759603990");
            str.add("_widget_1718759603983");

            List<String> str1 = new ArrayList<>();
            str1.add("_widget_1724038210699");
            SalesOrder salesOrder1 = ConnmeUtils.updateFields(salesOrder, str, str1, "_widget_1718759603981");

            Map<String, Object> parameterCxv = new HashMap<>();
            parameterCxv.put("app_id", "667230ad22a8581756b77d52");
            parameterCxv.put("entry_id", "667230b322a8581756b78353");
            HashMap<String, String> communti = new HashMap<>();
            communti.put("_widget_1718759603973", salesOrder1.get_widget_1718759603973());
            List<SalesOrder> salesOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SalesOrder.class);
            //排序最新的数据在前面
            salesOrders.sort(Comparator.comparing(SalesOrder::getCreateTime).reversed());


            Map<String, Object> parameterDelete = new HashMap<>();
            parameterDelete.put("instance_id", salesOrder.get_id());
            parameterDelete.put("tasks_type", 1);
            String jsonSale = JSONUtil.toJsonStr(parameterDelete);
            //销售单审核节点信息
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/workflow/instance/get", headers, jsonSale);
            JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
            int size = jdyPurchaseOrder.getTasks().size() - 1;
            Task task = jdyPurchaseOrder.getTasks().get(size);
            //数组
            if (salesOrders.size() == 1) {
                if (salesOrder1.get_widget_1721814819526() != null) {
                    salesOrder1.set_widget_1718759603988(DateUtil.offsetDay(task.getFinish_time(), salesOrder1.get_widget_1721814819526()));
                }else {
                    salesOrder1.set_widget_1718759603988(task.getFinish_time());
                }
            } else {
                if (salesOrder1.get_widget_1721814819526() == null) {
                    int i = 1;
                    boolean first = true;
                    while (first) {
                        if (salesOrders.get(i).getFlowState() == 1 && salesOrders.get(i).get_widget_1722592892210() != null) {
                            first = false;
                        } else {
                            if (salesOrders.size()-1==i){
                                first = false;
                            }else {
                                i++;
                            }

                        }
                    }
                    salesOrder1.set_widget_1718759603988(salesOrders.get(i).get_widget_1718759603988());
                } else {
                    salesOrder1.set_widget_1718759603988(DateUtil.offsetDay(task.getFinish_time(), salesOrder1.get_widget_1721814819526()));
                }
            }
            log.info("要求整单交货日期===>{},大小:{},时间：{}.time:{}", salesOrder1.get_widget_1718759603973(), salesOrders.size() , salesOrder1.get_widget_1718759603988(),task.getFinish_time());
            String s = ConnmeUtils.liuChen(salesOrder1.get_id());
            salesOrder1.set_widget_1730973345880(s);
            update(salesOrder1, headers);
        }


    }



    private void create(String data) {
        SalesOrder salesOrder = JSONUtil.toBean(data, SalesOrder.class);
        Header[] headers = ConnmeUtils.createHeaders();
        salesOrder.set_widget_1718759603978(null);
        List<String> str = new ArrayList<>();
        str.add("_widget_1718759603990");
        str.add("_widget_1718759603983");
        List<String> str1 = new ArrayList<>();
        str1.add("_widget_1724038210699");
        SalesOrder salesOrder1 = ConnmeUtils.updateFields(salesOrder, str, str1, "_widget_1718759603981");
        Map<String, Object> parameterCxv = new HashMap<>();
        parameterCxv.put("app_id", "667230ad22a8581756b77d52");
        parameterCxv.put("entry_id", "667230b322a8581756b78353");
        HashMap<String, String> communti = new HashMap<>();
        communti.put("_widget_1718759603973", salesOrder.get_widget_1718759603973());
        List<SalesOrder> salesOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SalesOrder.class);
        salesOrders.sort(Comparator.comparing(SalesOrder::getCreateTime).reversed());

        if (salesOrders.size() > 1) {
            int i = 1;
            boolean first = true;
            while (first) {
                if (salesOrders.size() == i) {
                    first = false;
                } else {
                    if (salesOrders.get(i).getFlowState() == 1) {
                        first = false;
                    } else {
                        i++;
                    }
                }
            }

            for (SalesOrder.ProductDetail productDetail : salesOrders.get(i).get_widget_1718759603981()) {
                for (SalesOrder.ProductDetail detail : salesOrder1.get_widget_1718759603981()) {
                    if (detail.get_widget_1718759603995().equals(productDetail.get_widget_1718759603995())) {
                        detail.set_widget_1722914939896(productDetail.get_widget_1722914939896());
                        detail.set_widget_1724057145593(productDetail.get_widget_1724057145593());
                    }
                }
            }
            update(salesOrder1, headers);
        }
    }

    private static void update(SalesOrder salesOrder1, Header[] headers) {
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "667230ad22a8581756b77d52");
        parameterInster.put("entry_id", "667230b322a8581756b78353");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", salesOrder1.get_id());
        salesOrder1.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(salesOrder1));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }
}
